import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'


import { Button, Table, Badge, Input, Tabs, Checkbox, Spin, Alert, Row, Col, Popconfirm, message } from 'antd'
const Search = Input.Search;
const TabPane = Tabs.TabPane;
import menuRoute from 'routes/menuRoute'
import debounce from 'lodash.debounce'

import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/agency-setting.scss'
import ResizeTable from "components/resize-table";
let tabCodeMap = {
  apply:1,
  approve:2,
  behalfOthers:3
} 

class AgencySetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      profileLoading: false,
      saveLoading: false,
      tab: 'apply',
      limitEdit: false, //员工权限编辑
      columns: [
        {title: messages('common.sequence'), dataIndex: 'serialNumber', width: 48, render: (text, record, index) => (
          <span>{this.state.pageSize * this.state.page + index + 1}</span>
        )},
        {title: messages('setting.key29'/*工号*/), dataIndex: 'emplyeeId'},
        {title: messages('setting.key30'/*姓名*/), dataIndex: 'userName', render: (name, record) => {
          return record.status === 1003 ?  //status:1003 已离职
            <div><span className='default-color-font'>{messages('setting.key31'/*离职*/)}</span> - {name}</div>  :
            name;
        }},
        {title: messages('setting.key32'/*部门*/), dataIndex: 'departmentName'},
        {title: messages('setting.key33'/*职务*/), dataIndex: 'dutyName', render: value => value || '-'},
        {title: messages('common.column.status'), dataIndex: 'enabled', width: '10%', render: isEnabled => (
          <Badge status={isEnabled ? 'success' : 'error'}
                 text={isEnabled ? messages('common.status.enable') : messages('common.status.disable')} />
        )},
        {
          title: messages('common.operation')/*操作(*/,
          dataIndex: 'operate',
          width: '10%',
          render: (text,record) => (
            <span>
              <Popconfirm placement="topLeft" onConfirm={(e) => this.handleDelete(e, record)} title={messages('my-agency.key11'/*你确认要删除？*/)}>
                <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
              </Popconfirm>
            </span>
        )}
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      keyWords: '', //搜索关键字
      companyProfile: {},
      profileDetail: {}, //代理权限配置
      agentDisabled: false,
      agentApplyEditable: false,
      agentApproveEditable: false,
      subApplicationPage: menuRoute.getRouteItem('sub-application','key'),    //子应用管理的页面项
      newAgency:  menuRoute.getRouteItem('new-agency','key'),    //新建代理
      agencyDetail:  menuRoute.getRouteItem('agency-detail','key'),    //代理详情
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentDidMount() {
    const { tenantMode } = this.props;
    if (!tenantMode) {
      this.setState({ tab: this.props.location.query.tab || 'apply' }, () => {
        this.getEmployeeLimit();
        this.getList()
      })
    }
    if (tenantMode) {
      this.getEmployeeLimitTenant();
    }
  }

  getList = () => {
    const { tab, page, pageSize, keyWords } = this.state;
    this.setState({ loading: true });
    agencyService.getAgencyList(tabCodeMap[tab], page, pageSize, keyWords).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    });
  };

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, ()=>{
        this.getList();
      })
  };

  //获取员工权限 集团模式下
  getEmployeeLimitTenant = () => {
    this.setState({ profileLoading: true });
    agencyService.getEmployeeLimitTenant().then(res => {
      this.setState({
        profileLoading: false,
        profileDetail: res.data,
        agentDisabled: res.data['all.Agent.Disable'],
        agentApplyEditable: res.data['All.AgentApply.Editable'],
        agentApproveEditable: res.data['All.AgentApprove.Editable']
      });
    });
  };

  //获取员工权限
  getEmployeeLimit = () => {
    this.setState({ profileLoading: true });
    agencyService.getEmployeeLimit().then(res => {
      this.setState({
        profileLoading: false,
        companyProfile: res.data,
        profileDetail: res.data.profileDetail,
        agentDisabled: res.data.profileDetail['all.Agent.Disable'],
        agentApplyEditable: res.data.profileDetail['All.AgentApply.Editable'],
        agentApproveEditable: res.data.profileDetail['All.AgentApprove.Editable']
      })
    })
  };

  //修改员工权限
  updateEmployeeLimit = () => {
    const { tenantMode } = this.props;
    const { companyProfile, profileDetail, agentDisabled, agentApplyEditable, agentApproveEditable } = this.state;
    profileDetail['all.Agent.Disable'] = agentDisabled;
    profileDetail['All.AgentApply.Editable'] = agentApplyEditable;
    profileDetail['All.AgentApprove.Editable'] = agentApproveEditable;
    companyProfile.profileDetail = profileDetail;
    this.setState({ saveLoading: true });
    this.setState({ companyProfile, profileDetail }, () => {
      if (!tenantMode) {
        agencyService.updateEmployeeLimit(companyProfile).then(res => {
          this.setState({
            saveLoading: false,
            limitEdit: false
          });
        });
      }
      if (tenantMode) {
        companyProfile.entityType = 2003;
        agencyService.updateEmployeeLimitTenant(companyProfile).then(res => {
          this.setState({
            saveLoading: false,
            limitEdit: false
          });
        });
      }
    })
  };

  //tab切换
  handleTabChange = (tab) => {
    this.setState({
      tab,
      page: 0,
      pagination: {
        total: 0
      }
    }, () => {
      this.getList()
    })
  };

  newAgency = () => {
    this.context.router.push(this.state.newAgency.url + `?tab=${this.state.tab}&tabKey=${tabCodeMap[this.state.tab]}`);
  };

  handleRowClick = (record) => {
    this.context.router.push(this.state.agencyDetail.url.replace(':principalOID', record.principalOID) + `?tab=${this.state.tab}&tabKey=${tabCodeMap[this.state.tab]}`);
  };

  handleDelete = (e, record) => {
    let params = {
      proxyOperationType: record.proxyOperationType,
      recordOID: record.recordOID
    };
    this.setState({ loading: true });
    agencyService.deleteAgencyItem(params).then(res => {
      message.success(messages('my-agency.key14'/*删除成功*/));
      this.setState({loading: false, page: 0}, () => {
        this.getList();
      });
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.operate.filed')/*操作失败(*/);
    });
  };

  //搜索 姓名／工号
  handleSearch= (value) => {
    this.setState({
      page: 0,
      keyWords: value,
      pagination: {
        current: 1
      }
    }, () => {
      this.getList();
    })
  };

  render(){
    const { loading, profileLoading, saveLoading, tab, limitEdit, columns, data, pagination, profileDetail,
      agentDisabled } = this.state;
    const { tenantMode } = this.props;
    let message = messages('setting.key1503')/*如需开启/禁用该功能，请前往【APP应用管理 - 代理设置】页面*/ + '：';
    const description = (
      <div>
        <Row span={20} style={{marginBottom: 5}}>1、{messages('setting.key1504')/*将该应用状态设置为【启用】，用户可在【APP-应用】界面 看到该应用。*/}</Row>
        <Row span={20} style={{marginBottom: 5}}>2、{messages('setting.key1505')/*将该应用状态设置为【禁用】，该应用将不在【APP-应用】中显示。*/}</Row>
      </div>
    );
    return (
      <div className="agency-setting">
        <div style={{marginBottom: 20}}>
          <Alert
            message={message}
            description={description}
            type="info"
            showIcon
            closable
          />
        </div>
        <div className="limits-setting">
          <Spin spinning={profileLoading}>
            <div className="title">{messages('setting.key34'/*员工权限*/)}：</div>
            {limitEdit ? (
              <div className="setting">
                <div className="show">
                  {!agentDisabled && (
                    <span>
                      <span className="ant-divider"/>
                      {messages('setting.key35'/*员工可编辑代理制单设置*/)}：
                      <Checkbox defaultChecked={profileDetail['All.AgentApply.Editable']}
                                onChange={(e) => {this.setState({ agentApplyEditable: e.target.checked })}}/>
                      <span className="ant-divider"/>
                      {messages('setting.key36'/*员工可编辑代理审批设置*/)}：
                      <Checkbox defaultChecked={profileDetail['All.AgentApprove.Editable']}
                                onChange={(e) => {this.setState({ agentApproveEditable: e.target.checked })}}/>
                    </span>
                  )}
                </div>
                <div className="edit-btn">
                  <Button type="primary" className="save-btn" loading={saveLoading} onClick={this.updateEmployeeLimit}>{messages('common.save')}</Button>
                  <Button onClick={() => {this.setState({limitEdit: false})}}>{messages('common.cancel')}</Button>
                </div>
              </div>
            ) : (
              <div className="show">
                {!agentDisabled && (
                  <span>
                    {messages('setting.key35'/*员工可编辑代理制单设置*/)}：
                    {profileDetail['All.AgentApply.Editable'] ? messages('setting.key37'/*允许*/) : messages('setting.key38'/*禁止*/)}
                    <span className="ant-divider"/>
                    {messages('setting.key36'/*员工可编辑代理审批设置*/)}：
                    {profileDetail['All.AgentApprove.Editable'] ? messages('setting.key37'/*允许*/) : messages('setting.key38'/*禁止*/)}
                  </span>
                )}
                <a className="edit" onClick={() => {this.setState({limitEdit: true})}}>{messages('common.edit')}</a>
              </div>
            )}
          </Spin>
        </div>
        {tenantMode && (
          <div style={{color: '#ccc'}}>
            {messages('setting.key2215')/*说明：具体代理规则需要在公司模式下设置*/}
          </div>
        )}
        {!tenantMode && (
          <div>
            <Tabs type={"card"} activeKey={tab} onChange={this.handleTabChange}>
              <TabPane tab={messages('setting.key39'/*代理制单*/)} key="apply" />
              <TabPane tab={messages('setting.key40'/*代理审批*/)} key="approve" />
              <TabPane tab={messages('setting.key2832'/*代做账本代还款*/)} key="behalfOthers" />
            </Tabs>
            <div className="table-header">
              <div className="table-header-title">{messages("common.total", {total: pagination.total || 0})}</div>
              <div className="table-header-buttons">
                <Button type="primary" onClick={this.newAgency}>
                  {tab === 'apply' && messages('setting.key41'/*新建代理制单*/)}
                  {tab === 'approve' && messages('setting.key42'/*新建代理审批权限*/)}
                  {tab === 'behalfOthers' && messages('setting.key2833'/*新建代理制单*/)}
                    
                </Button>
                <Search placeholder={messages('setting.key6'/*请输入姓名/工号*/)}
                        className="search-input"
                        onChange={e => this.handleSearch(e.target.value)}/>
              </div>
            </div>
            <ResizeTable
              rowKey="recordOID"
              columns={columns}
              dataSource={data}
              pagination={pagination}
              loading={loading}
              onRow={record => ({
                onClick: () => this.handleRowClick(record)
              })}
              bordered
              size="middle"
            />
          </div>
        )}
      </div>
    )
  }

}

AgencySetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(AgencySetting);
